package com.file.parser.socialsecurity;

import com.file.bo.ResponseData;
import com.file.bo.socialsecurity.HunanIndividualRecordSheet;
import com.file.bo.socialsecurity.HunanInsuranceParticipation;
import com.file.constant.ErrorCode;
import com.file.parser.BasePdfParser;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.*;
import technology.tabula.detectors.SpreadsheetDetectionAlgorithm;
import technology.tabula.extractors.SpreadsheetExtractionAlgorithm;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class HunanSocialSecurityPdfParser extends BasePdfParser {

    public ResponseData<String> parseHunanSocialSecurityPdfParser(String daId, String filePath) {
        log.info("parseHunanSocialSecurityPdfParser started, daId:{}", daId);
        String json = null;
        try {
            if (filePath.contains("cbzm")) {
                HunanInsuranceParticipation hunanInsuranceParticipation = parseHunanInsuranceParticipation(filePath);
                json = JsonUtils.convertObjectToJson(hunanInsuranceParticipation);
            } else if (filePath.contains("qyd")) {//NOSONAR
                HunanIndividualRecordSheet hunanIndividualRecordSheet = parseHunanIndividualRecordSheet(filePath);
                json = JsonUtils.convertObjectToJson(hunanIndividualRecordSheet);//NOSONAR
            } else {
                log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseHunanSocialSecurityPdfToJson failed, new type not supported");
                return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(), ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
            }
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseHunanSocialSecurityPdfToJson failed", e);
            return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(), ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseHunanSocialSecurityPdfToJson completed, daId:{}", daId);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private HunanIndividualRecordSheet parseHunanIndividualRecordSheet(String filePath) { //NOSONAR
        HunanIndividualRecordSheet hunanIndividualRecordSheet = new HunanIndividualRecordSheet();
        return hunanIndividualRecordSheet;
    }

    private void parseListToBO(List<List<String>> rowList, HunanInsuranceParticipation hunanInsuranceParticipation) {
        String sectionName = "";
        List<HunanInsuranceParticipation.InsuranceRelation> insuranceRelations = new ArrayList<>();
        List<HunanInsuranceParticipation.PaymentDetail> paymentDetails = new ArrayList<>();
        String unifiedCreditCode = "", unitName = "", insuranceType = "", feePeriod = "";
        for (int i = 0; i < rowList.size(); i++) {
            List<String> cellList = rowList.get(i);
            if (StringUtils.equals(cellList.get(0), "当前单位名称")) {
                sectionName = "个人基本信息";
            } else if (StringUtils.equals(cellList.get(0), "统一社会信用代码")) {
                sectionName = "参保关系";
            } else if (StringUtils.equals(cellList.get(0), "缴费明细")) {
                sectionName = "";
            } else if (StringUtils.equals(cellList.get(0), "费款所属期")) {
                sectionName = "缴费明细";
            }
            switch (sectionName) {  //NOSONAR
                case "个人基本信息":
                    if (StringUtils.equals(cellList.get(0), "当前单位名称")) {
                        hunanInsuranceParticipation.setCurrentUnitName(cellList.get(1));
                        hunanInsuranceParticipation.setCurrentUnitNumber(cellList.get(3));
                        hunanInsuranceParticipation.setBranchUnit("");
                    } else if (StringUtils.equals(cellList.get(0), "分支单位")) {
                        hunanInsuranceParticipation.setBranchUnit(StringUtils.isEmpty(cellList.get(1)) ? "" : cellList.get(1));
                    } else if (StringUtils.equals(cellList.get(0), "姓名")) {
                        hunanInsuranceParticipation.setName(cellList.get(1));
                        hunanInsuranceParticipation.setAccountOpeningTime(cellList.get(3));
                        hunanInsuranceParticipation.setIdCardNumber(cellList.get(5));
                    } else if (StringUtils.equals(cellList.get(0), "性别")) {
                        hunanInsuranceParticipation.setGender(cellList.get(1));
                        hunanInsuranceParticipation.setHandlingInstitutionName(cellList.get(3));
                        hunanInsuranceParticipation.setValidUntil(cellList.get(5));
                    } else if (StringUtils.isEmpty(cellList.get(0)) && StringUtils.startsWith(cellList.get(1), "1.")) {
                        hunanInsuranceParticipation.setRemark(cellList.get(1));
                    } else if (StringUtils.equals(cellList.get(0), "用途")) {
                        hunanInsuranceParticipation.setPurpose(StringUtils.isEmpty(cellList.get(1)) ? "" : cellList.get(1));
                    }
                    break;
                case "参保关系":
                    if (StringUtils.equals(cellList.get(0), "统一社会信用代码")) {
                        break;
                    } else if (!cellList.stream().allMatch(String::isEmpty)) {
                        HunanInsuranceParticipation.InsuranceRelation insuranceRelation = new HunanInsuranceParticipation.InsuranceRelation();
                        if (StringUtils.isNoneEmpty(cellList.get(0))) {
                            unifiedCreditCode = cellList.get(0);
                            unitName = cellList.get(1);
                            insuranceRelation.setUnifiedCreditCode(cellList.get(0));
                            insuranceRelation.setUnitName(cellList.get(1));
                            insuranceRelation.setInsuranceType(cellList.get(2));
                            insuranceRelation.setStartEndTime(cellList.get(3));
                        } else if (StringUtils.isNoneEmpty(cellList.get(2))) {
                            insuranceRelation.setUnifiedCreditCode(unifiedCreditCode);
                            insuranceRelation.setUnitName(cellList.get(2));
                            insuranceRelation.setInsuranceType(cellList.get(3));
                            insuranceRelation.setStartEndTime(cellList.get(4));
                        } else if (StringUtils.isNoneEmpty(cellList.get(5))) {
                            insuranceRelation.setUnifiedCreditCode(unifiedCreditCode);
                            insuranceRelation.setUnitName(unitName);
                            insuranceType = cellList.get(5);
                            insuranceRelation.setInsuranceType(cellList.get(5));
                            insuranceRelation.setStartEndTime(cellList.get(6));
                        } else {
                            insuranceRelation.setUnifiedCreditCode(unifiedCreditCode);
                            insuranceRelation.setUnitName(unitName);
                            insuranceRelation.setInsuranceType(insuranceType);
                            insuranceRelation.setStartEndTime(cellList.get(7));
                        }
                        insuranceRelations.add(insuranceRelation);
                    }
                    break;
                case "缴费明细":
                    if (StringUtils.equals(cellList.get(0), "费款所属期")) {
                        break;
                    }
                    HunanInsuranceParticipation.PaymentDetail detail = new HunanInsuranceParticipation.PaymentDetail();
                    if (cellList.get(0).matches("[0-9]{6}")) {
                        feePeriod = cellList.get(0);
                    }
                    if (StringUtils.isEmpty(cellList.get(0)) || cellList.get(0).matches("[0-9]{6}")) {
                        detail.setFeePeriod(feePeriod);
                        detail.setInsuranceType(cellList.get(1));
                        detail.setPaymentBase(cellList.get(2));
                        detail.setUnitShouldPay(cellList.get(3));
                        detail.setIndividualShouldPay(cellList.get(4));
                        detail.setPaymentFlag(cellList.get(5));
                        detail.setPaymentDate(cellList.get(6));
                        detail.setPaymentType(cellList.get(7));
                        detail.setHandlingInstitution(cellList.get(8));
                        paymentDetails.add(detail);
                    } else {
                        detail.setFeePeriod(feePeriod);
                        detail.setInsuranceType(cellList.get(0));
                        detail.setPaymentBase(cellList.get(1));
                        detail.setUnitShouldPay(cellList.get(2));
                        detail.setIndividualShouldPay(cellList.get(3));
                        detail.setPaymentFlag(cellList.get(4));
                        detail.setPaymentDate(cellList.get(5));
                        detail.setPaymentType(cellList.get(6));
                        detail.setHandlingInstitution(cellList.get(7));
                        paymentDetails.add(detail);
                    }

            }
        }
        hunanInsuranceParticipation.setInsuranceRelations(insuranceRelations);
        hunanInsuranceParticipation.setPaymentDetails(paymentDetails);
    }

    private List<List<String>> parseFileToRowList(String filePath) {
        // 1. 读取文件
        File pdf = new File(filePath);

        //页面所有table的记录，每一个元素代表下面一条记录cellList
        List<List<String>> rowList = new ArrayList<>();

        // 2. pdfbox读取PDDocument
        try (PDDocument pdfDocument = PDDocument.load(pdf)) {
            // 3. tabula新建ObjectExtractor和NurminenDetectionAlgorithm，同时准备接收表格Rectangle的结构
            ObjectExtractor objectExtractor = new ObjectExtractor(pdfDocument);
            SpreadsheetDetectionAlgorithm detectionAlgorithm = new SpreadsheetDetectionAlgorithm();
            Map<Integer, List<Rectangle>> pageNumber2RectangleListMap = new HashMap<>();//key为页的序号， value为对应的Rectangle的list

            // 4. 获取每页的PageIterator
            PageIterator pageIterator = objectExtractor.extract();

            // 5. 解析每页的Rectangle
            // 如果单页pdf中有多个Rectangle，则解析出来的List<Rectangle>会有多个对象
            while (pageIterator.hasNext()) {
                Page page = pageIterator.next();
                List<Rectangle> rectangleList = detectionAlgorithm.detect(page);
                if (rectangleList.size() > 0) {
                    pageNumber2RectangleListMap.put(page.getPageNumber(), rectangleList);
                }
            }

            // 6.通过table位置获取表格具体内容
            SpreadsheetExtractionAlgorithm extractionAlgorithm = new SpreadsheetExtractionAlgorithm();

            // 如果单页pdf中有多个表格，则解析出来的List<Rectangle>会有多个对象
            for (Map.Entry<Integer, List<Rectangle>> entry : pageNumber2RectangleListMap.entrySet()) {
                Page page = objectExtractor.extract(entry.getKey());
                Rectangle rectangle = null;

                List<Rectangle> rectangleList = entry.getValue();
                for (Rectangle r : rectangleList) {
                    double rectangleHeight = r.getHeight();
                    if (Double.compare(rectangleHeight, 0) > 0) {
                        rectangle = r;
                        break;
                    }
                }
                if (rectangle == null) {
                    throw new RuntimeException("rectangle is null.");
                }

                if (entry.getKey() > 1) {
                    rectangle.setTop(rectangle.getTop());
                }
                rectangle.setBottom(rectangle.getBottom() + 500);
                Page area = page.getArea(rectangle);

                // 如果每页有多个表格，解析每一个table
                List<Table> tableList = extractionAlgorithm.extract(area);
                for (Table table : tableList) {
                    for (int i = 0; i < table.getRowCount(); i++) {
                        List<String> cellList = new ArrayList<>();//一条记录，每个单元格占一个元素
                        for (int j = 0; j < table.getColCount(); j++) {
                            cellList.add(table.getCell(i, j).getText(false));
                        }
                        rowList.add(cellList);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        return rowList;
    }

    private HunanInsuranceParticipation parseHunanInsuranceParticipation(String filePath) {
        HunanInsuranceParticipation hunanInsuranceParticipation = new HunanInsuranceParticipation();
        String pdfText = getPdfTextByStripper(filePath).replace(System.getProperty("line.separator", "\n"), StringUtils.EMPTY);
        String personName = pdfText.substring(pdfText.indexOf("个人姓名：") + 5, pdfText.indexOf("第1页")).trim();
        hunanInsuranceParticipation.setPersonName(personName);
        String personId = pdfText.substring(StringUtils.lastIndexOf(pdfText, "个人编号：") + 5).trim();
        hunanInsuranceParticipation.setPersonID(personId);
        List<List<String>> rowList = parseFileToRowList(filePath);
        parseListToBO(rowList, hunanInsuranceParticipation);
        return hunanInsuranceParticipation;
    }

    public static void main(String[] args) {
        HunanSocialSecurityPdfParser hunanSocialSecurityPdfParser = new HunanSocialSecurityPdfParser();
        String json, filePath;
        //  参保证明
        filePath = "D:\\data\\file\\socialsecurity\\湖南\\zd4akdkf1724794149731086336_app-gjzwfw-dzsb_origins\\app-gjzwfw-dzsb_cbzm.pdf";
        json = hunanSocialSecurityPdfParser.parseHunanSocialSecurityPdfParser("", filePath).getData();
        System.out.println("json = " + json);

        filePath = "D:\\data\\file\\socialsecurity\\湖南\\zd4akdkf1727994679046098944_app-gjzwfw-dzsb_origins\\app-gjzwfw-dzsb_cbzm.pdf";
        json = hunanSocialSecurityPdfParser.parseHunanSocialSecurityPdfParser("", filePath).getData();
        System.out.println("json = " + json);

        filePath = "D:\\data\\file\\socialsecurity\\湖南\\zd4akdkf1724795784913514496_app-gjzwfw-dzsb_origins\\app-gjzwfw-dzsb_cbzm.pdf";
        json = hunanSocialSecurityPdfParser.parseHunanSocialSecurityPdfParser("", filePath).getData();
        System.out.println("json = " + json);

        filePath = "D:\\data\\file\\socialsecurity\\湖南\\zd4akdkf1742775500463173632_app-gjzwfw-dzsb_origins\\app-gjzwfw-dzsb_cbzm.pdf";
        json = hunanSocialSecurityPdfParser.parseHunanSocialSecurityPdfParser("", filePath).getData();
        System.out.println("json = " + json);

    }

}
